<script setup lang="ts">
import { AxiosError } from 'axios'
import { getPublicKey } from '~@/api/auth'
import { loginByThird } from '~@/api/common/login'
import { ResponseCode } from '~@/api/response.code'
import { encryptByRSA } from '~@/utils/crypto'

const route = useRoute()
const router = useRouter()
const params = route.params
const notification = useNotification()
const token = useAuthorization()
// if (path)
//     router.replace(path)
// else router.replace('/')

const code: string = params?.code ? decodeURIComponent(params.code as string) : ''
// const state: string = params?.state ? decodeURIComponent(params.state as string) : ''
// const target: string = params?.target ? decodeURIComponent(params.target as string) : ''
let publicKey: string = ''

async function loadPublicKey() {
    const res = await getPublicKey()
    if (res && res.code === ResponseCode.SUCCESS) {
        if (res.data) {
            publicKey = res.data
            login()
        }
    }
}

async function login() {
    const params = new FormData()
    params.append('code', encryptByRSA(publicKey, code) as string)
    params.append('thirdType', encryptByRSA(publicKey, '0') as string)
    params.append('scope', 'user')
    try {
        const { data, message } = await loginByThird(params)
        if (data) {
            token.value = `Bearer ${data}`
            notification.success({
                message: '登录成功',
                description: '欢迎回来！',
                duration: 3,
            })
            // 获取当前是否存在重定向的链接，如果存在就走重定向的地址
            router.push({
                path: '/',
                replace: true,
            })
        }
        else {
            notification.error({
                message: '登录失败',
                description: message || '未知原因',
                duration: 3,
            })
        }
    }
    catch (e) {
        if (e instanceof AxiosError) {
            notification.error({
                message: '登录失败',
                description: '未知原因',
                duration: 3,
            })
        }
    }
}

onMounted(() => {
    loadPublicKey()
})
</script>

<template>
    <div>
        <h1>正在登录...</h1>
    </div>
</template>
